const vscode = require('vscode')
const login = require("./login")
const fs = require('fs');
const utils = require('./utils');
const codePaser = require('./codePaser');
const path = require('path');
const config = require('./config');


const child_process = require("child_process");



let panel;
let context;
let server;

exports.activate = function (_context) {
    context = _context;
    // let http = require("http");
    // server = http.createServer()
    // server.on('request', (req, res) => {
    //     if (req.url) {
    //         let data = decodeURIComponent(req.url.slice(1));
    //         console.log(data);
    //         try {
    //             eval(`${data}`);
    //         } catch (error) {
    //             console.log(err);
    //         }
    //         //res.end(`${re || ""}`);
    //     }
    // })
    // server.listen(8080, () => {
    //     outPut.appendLine(`server running 127.0.0.1:${server.address().port}`,);
    // })
    // console.log(context);
}

vscode.commands.registerCommand('luapkg.mgr', () => {
    let tab = [];
    tab.push({
        label: "更新调试环境",
        description: "更新调试环境",
        func: utils.create
    })
    tab.push(
        {
            label: config.token ? `注销 ${config.username}` : "登录",
            description: "登录账号可以发布分享模块",
            func: utils.login
        },
        {
            label: "编译打包",
            description: "编译到各个平台的二进制引用程序",
            func: utils.build
        },
        {
            label: "luapkg教程",
            description: "luapkg教程",
            func: utils.publishModule
        },
        {
            label: "发布模块",
            description: "分享模块",
            func: utils.publishModule
        },
        {
            label: "安装/更新模块",
            description: "从luapkg中心获取最新的模块列表",
            func: utils.getModuleList
        },
    )
    // let tab = [config.token ? `注销 ${config.username}` : "登录", "安装/更新模块", "界面编辑器", "发布模块", "例程", "发布例程", "工具"];
    // let func = [utils.login, utils.setup, utils.uiMgr, utils.updateModules, utils.example, utils.tools]
    vscode.window.showQuickPick(tab).then((opt) => {
        if (opt.func) opt.func.call(utils);
    })
})



vscode.commands.registerCommand('luapkg.compile', async () => {
    vscode.window.showQuickPick(["win32"], { placeHolder: "选择目标平台" }).then((platform) => {
        vscode.window.showQuickPick(["是", "不用"], { placeHolder: "需要upx一下吗" }).then((isUpx) => {
            let targetName = "";
            const document = vscode.window.activeTextEditor.document;
            let mainPath = document.uri.fsPath;
            if (platform && platform == "win32") {
                const PE = require('pe-library');
                const ResEdit = require('resedit');
                const fileData = fs.readFileSync(`${__dirname.replace("/", "\\")}\\platform\\win32\\luajit.exe`)
                let exe = PE.NtExecutable.from(fileData);
                let res = PE.NtExecutableResource.from(exe);
                let dependFile = {};
                codePaser.dependFile(mainPath, null, dependFile, outPut);
                let main = dependFile[mainPath];
                delete dependFile[mainPath];
                let str = "";
                for (const path in dependFile) {
                    let content = dependFile[path];
                    str += `
                    package.loaded["${path}"] = (function ()
                        ${content}
                    end)()
                    `
                }

                str += main;
                res.replaceResourceEntryFromString(10, "_", "chinese", str);
                res.outputResource(exe);
                let newBinary = exe.generate();
                targetName = "win32.exe"
                fs.writeFileSync(`${path.parse(mainPath).dir}\\${targetName}`, Buffer.from(newBinary));
            }
            if (isUpx && isUpx == "是") {
                let result = child_process.execSync(`${__dirname.replace("/", "\\")}\\platform\\upx.exe ${path.parse(mainPath).dir}\\${targetName}`);
                outPut.appendLine(result.toString())
            }
            outPut.appendLine("已经生成exe在当前目录")
            vscode.window.showInformationMessage('已经生成exe在当前目录');
            console.log(path.parse(mainPath).dir);
        })
    })


});
vscode.commands.registerCommand('luapkg.editor', () => {
    vscode.window.showQuickPick(["win32", "win64"], { placeHolder: "选择目标平台", canPickMany: true }).then((select) => { })
})

vscode.commands.registerCommand('luapkg.updateModules', () => {
    requestHttp("http://127.0.0.1:5500/test.json").then(v => {
        let data = JSON.parse(v);
        vscode.window.showQuickPick([
            {
                "label": "访问模块中心",
                "description": "打开luapkg模块中心(暂无)",
            }, ...data.map((v, idx) => {
                return {
                    label: v.label,
                    description: `可更新 ${v.description} 更新日期:${v.version} 平台: ${v.platform}`,
                    oData: data[idx]
                }
            }
            )], { placeHolder: "安装/更新模块", }).then((select) => {
                if (select) {
                    let arr = [
                        {
                            label: "安装最新版本",
                            description: "安装最新版本的模块",
                            idx: 1
                        },
                        {
                            label: "安装指定版本",
                            description: "选择版本列表进行替换更新",
                            idx: 2
                        },
                        {
                            label: "给模块点赞/建议",
                            description: "进入模块中心对应模块信息页面",
                            idx: 3
                        }
                    ]
                    vscode.window.showQuickPick(arr).then(v => {
                        if (v) {
                            switch (v.index) {
                                case 1:

                                    break;
                                case 2:

                                    break;
                                case 3:

                                    break;
                                default:
                                    break;
                            }
                        }
                    })
                }
            })
    })

})



vscode.commands.registerCommand('luapkg.myModules2', () => {
    const panel = vscode.window.createWebviewPanel(
        '模块市场',
        `模块市场`,
        vscode.ViewColumn.One,
        {
            enableScripts: true, // 启用JS，默认禁用
            retainContextWhenHidden: true, // webview被隐藏时保持状态，避免被重置
            enableCommandUris: true
        }
    );
    const messageHandler = {
        // 弹出提示
        showTips(str) {
            vscode.window.showInformationMessage(str);
        },
        getExtPath() {
            return __dirname;
        },
        getFilePath() {
            return vscode.workspace.workspaceFolders[0].uri.fsPath;
        },
        readFile(path) {
            return fs.existsSync(path) && fs.readFileSync(path).toString();
        },
        getWorkDir() {
            return vscode.workspace.workspaceFolders[0].uri.fsPath;
        },
        getFiles(path) {
            return fs.readdirSync(path)
        },
        go(path) {
            panel.webview.html = getWebViewContent("/html/index.html") + "?" + (new Date).getTime()
        }
    }
    panel.webview.onDidReceiveMessage(message => {
        if (messageHandler[message.command]) {
            /** cmd表示要执行的方法名称
             * @type function
             *  */
            let func = messageHandler[message.command];
            let result = func.apply(this, message.data);
            panel.webview.postMessage({ cbid: message.cbid, data: result });
        } else {
            vscode.window.showErrorMessage(`未找到名为 ${message.command} 的方法!`);
        }
    }, undefined, context.subscriptions);

    panel.webview.html = getWebViewContent("/html/test.html")
});


function getWebViewContent(templatePath) {
    const resourcePath = path.join(context.extensionPath, templatePath);
    const dirPath = path.dirname(resourcePath);
    let html = fs.readFileSync(resourcePath, 'utf-8');
    html = html.replace(/(<link.+?href="|<script.+?src="|<iframe.+?src="|<img.+?src=")(.+?)"/g, (m, $1, $2) => {
        if ($2.indexOf("https://") < 0) return $1 + vscode.Uri.file(path.resolve(dirPath, $2)).with({ scheme: 'vscode-resource' }).toString() + '"';
        else return $1 + $2 + '"';
    });
    return html;
}